package org.fuxia.im.core.service.impl;

import java.nio.channels.SocketChannel;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Random;

import javax.annotation.Resource;

import org.fuxia.im.core.entries.ECPacket;
import org.fuxia.im.core.entries.ECResponse;
import org.fuxia.im.core.entries.ECSession;
import org.fuxia.im.core.iconst.ServerConst;
import org.fuxia.im.core.server.ECSessionMananger;
import org.fuxia.im.core.service.ECService;
import org.fuxia.im.core.socket.impl.ECNioServer;
import org.fuxia.im.db.dao.ChatGroupDaoImpl;
import org.fuxia.im.db.dao.UserDaoImpl;
import org.fuxia.im.db.dao.UserGroupDaoImpl;
import org.fuxia.im.entities.ChatGroup;
import org.fuxia.im.entities.User;
import org.fuxia.im.entities.UserGroup;

@SuppressWarnings("unchecked")
public class RegisterUserService implements ECService
{
	private static final DateFormat	sdf				= new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
	private static final DateFormat	codeSdf			= new SimpleDateFormat("yyMM");
	private String					errorMessage	= null;

	@Resource
	private UserDaoImpl				userDAO;
	
	@Resource
	private UserGroupDaoImpl userGroupDao ;

	public void service(ECPacket packet)
	{
		String sessionId = packet.getParameter(ServerConst.SESSION_ID.name());
		ECSession session = ECSessionMananger.getInstance().getSession(sessionId);
		SocketChannel channel = session.getChannel();
		ECResponse resp = new ECResponse();

		String idCard = packet.getParameter("idCard");
		resp.setResponseType("RESPONSE");
		String userCode = generateUserCode();
		if (validateIdCard(idCard) && userCode != null)
		{
			String password = packet.getParameter("password");
			String nickName = packet.getParameter("nickName");
			String birthDay = packet.getParameter("birthDay");
			String address = packet.getParameter("address");
			String sex = packet.getParameter("sex").equals("1")?"男":"女";

			User u = new User();
			u.setUserCode(userCode);
			u.setAddress(address);
			u.setBirthDay(birthDay);
			u.setCreateDate(sdf.format(new Date()));
			u.setIdCard(idCard);
			u.setAge(0);
			u.setSex(sex);
			u.setImagePath("images/default.jpg");
			u.setIsDiable(false);
			u.setPassword(password);
			u.setNickName(nickName);
			try
			{
				userDAO.save(u);
				resp.setStatusCode(200);
				resp.setResponseText("用户注册成功,请牢记你的账户【" + userCode + "】");
				
				UserGroup cg1 = new UserGroup() ;
				cg1.setGroupName("所有好友");
				cg1.setUserCode(userCode);
				
				UserGroup cg2 = new UserGroup() ;
				cg2.setGroupName("陌生人");
				cg2.setUserCode(userCode);
				userGroupDao.saveOrUpdate(cg1);
				userGroupDao.saveOrUpdate(cg2);
			}
			catch (Exception e)
			{
				resp.setStatusCode(400);
				resp.setResponseText("用户注册失败");
			}

		}
		else
		{
			resp.setStatusCode(400);
			resp.setResponseText(errorMessage);
		}
		try
		{
			ECNioServer.writeResponse(resp, channel);
		}
		catch (Exception e)
		{
			e.printStackTrace();
		}

	}

	private boolean validateIdCard(String idCard)
	{
		boolean result = false;
		String hql = "select 1 from IMUser where idCard=:idCard";
		try
		{
			List<Object> obj = userDAO.findByNamedParam(hql, new String[] { "idCard" }, new String[] { idCard });
			result = obj == null ? true : obj.size() > 0 ? false : true;
		}
		catch (Exception e)
		{
			errorMessage = "服务器出现问题";
		}

		if (!result)
		{
			errorMessage = "身份证信息重复";
			return result;
		}

		return result;
	}

	private String generateUserCode()
	{
		String userCode = null;
		boolean result = false;
		String hql = "select 1 from IMUser where userCode=:userCode";
		while (!result)
		{
			userCode = generateCode();
			try
			{
				List<Object> obj = userDAO
						.findByNamedParam(hql, new String[] { "userCode" }, new String[] { userCode });
				result = obj == null ? true : obj.size() > 0 ? false : true;
				if (!result)
				{
					return userCode;
				}
			}
			catch (Exception e)
			{
				errorMessage = "服务器出现问题";
				return null;
			}
		}

		return userCode;
	}

	/**
	 * 生成用户账号
	 * 
	 * @return
	 */
	private String generateCode()
	{
		Random rd = new Random();
		int bit = rd.nextInt(9);
		bit = bit >= 6 ? bit : 9 - bit;
		String[] ca = new String[bit];
		StringBuffer code = new StringBuffer();
		for (char c : codeSdf.format(new Date()).toCharArray())
		{
			int index = rd.nextInt(bit - 2) + 1;
			while (ca[index] != null)
			{
				index = rd.nextInt(bit - 1);
			}
			ca[index] = String.valueOf(c);
		}
		for (int i = 1; i < ca.length; i++)
		{
			if (ca[i] == null)
			{
				ca[i] = String.valueOf(rd.nextInt(10));
			}
			code.append(ca[i]);
		}
		code.insert(0, String.valueOf(rd.nextInt(9 - 1) + 1));
		return code.toString();
	}

}
